package org.fpp.objectpool;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class ObjectPoolExample {
    public static void main(String[] args) {
        // Create a factory for creating objects to be pooled
        ObjectFactory factory = new ObjectFactory();
        // Create a configuration for the pool
        GenericObjectPoolConfig<MyObject> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(10); // Maximum number of objects in the pool
        config.setMaxIdle(5); // Maximum number of idle objects in the pool
        // Create the object pool
        ObjectPool<MyObject> objectPool = new GenericObjectPool<>(factory, config);
        // Use the object pool
        try {
            objectPool.addObject();
            MyObject obj1 = objectPool.borrowObject();
            // Do something with obj1
            System.out.println("Object 1: " + obj1);
            objectPool.returnObject(obj1);
            MyObject obj2 = objectPool.borrowObject();
            // Do something with obj2
            System.out.println("Object 2: " + obj2);
            // Return the objects to the pool
            objectPool.returnObject(obj2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Close the object pool
        objectPool.close();
    }
}

class ObjectFactory extends BasePooledObjectFactory<MyObject> {
    @Override
    public MyObject create() {
        // Create a new instance of MyObject
        return new MyObject();
    }

    @Override
    public PooledObject<MyObject> wrap(MyObject obj) {
        // Wrap the object in a PooledObject
        return new DefaultPooledObject<>(obj);
    }
}

class MyObject {
    // Your custom object class
    // Add your logic here
}